package com.codingfuture.glaciercollect.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.codingfuture.glaciercollect.dto.THDateDTO;
import com.codingfuture.glaciercollect.entity.Meter;
import com.codingfuture.glaciercollect.entity.MeterRecord;
import com.codingfuture.glaciercollect.mapper.MeterMapper;
import com.codingfuture.glaciercollect.mapper.MeterRecordMapper;
import com.codingfuture.glaciercollect.service.MeterRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Author: Sun
 * @DateTime: 2025/4/10 17:57
 * @Description:
 **/
@Service
public class MeterRecordServiceImpl implements MeterRecordService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MeterRecordMapper meterRecordMapper;
    @Autowired
    private MeterMapper meterMapper;

    @Cacheable("meter_list")
    @CacheEvict(value = "meter_record_date", allEntries = true)
    @Override
    @Transactional
    public Boolean addInfor(THDateDTO thDateDTO) {
        QueryWrapper<Meter> wrapper = new QueryWrapper<>();
        wrapper.eq("name", thDateDTO.getSn());
        List<Meter> meters = meterMapper.selectList(wrapper);


        MeterRecord meterRecord = new MeterRecord();

        meterRecord.setId(null);
        meterRecord.setHum(thDateDTO.getHum());
        meterRecord.setCompanyId(meters.get(0).getCompanyId());
        meterRecord.setMeterId(meters.get(0).getId());
        meterRecord.setTem(thDateDTO.getTem());
        meterRecord.setMeterSn(meters.get(0).getSn());
        meterRecord.setMeterName(thDateDTO.getSn());
        meterRecord.setHostSn(meters.get(0).getHostSn());
        meterRecord.setHostName(meters.get(0).getHostName());
        meterRecord.setWarehouseSn(meters.get(0).getWarehouseSn());
        meterRecord.setWarehouseName(meters.get(0).getWarehouseName());
        meterRecord.setWarehouseId(meters.get(0).getWarehouseId());
        meterRecord.setCompanyName(meters.get(0).getCompanyName());
        meterRecord.setMaxHum(meters.get(0).getMaxHum());
        meterRecord.setMinHum(meters.get(0).getMinHum());
        meterRecord.setMaxTem(meters.get(0).getMaxTem());
        meterRecord.setMinTem(meters.get(0).getMinTem());
        meterRecord.setCreateTime(LocalDateTime.now());
        meterRecord.setWarehouseId(meters.get(0).getWarehouseId());
        meterRecord.setHostId(meters.get(0).getHostId());
        System.err.println(meters);
        return meterRecordMapper.insert(meterRecord) > 0;
    }
//    stream流的写法
//    // 查询对应的仪表信息
//    QueryWrapper<Meter> wrapper = new QueryWrapper<>();
//    wrapper.eq("name", thDateDTO.getSn());
//    List<Meter> meters = meterMapper.selectList(wrapper);
//
//    // 使用Stream处理查询结果，避免直接索引访问导致的NPE
//    return meters.stream()
//            .findFirst()  // 获取第一个元素（如果存在）
//        .map(meter -> {  // 转换为MeterRecord对象
//        MeterRecord record = new MeterRecord();
//        record.setId(null);
//        record.setHum(thDateDTO.getHum());
//        record.setCompanyId(meter.getCompanyId());
//        record.setMeterId(meter.getId());
//        record.setTem(thDateDTO.getTem());
//        record.setMeterSn(meter.getSn());
//        record.setMeterName(thDateDTO.getSn());
//        record.setHostSn(meter.getHostSn());
//        record.setHostName(meter.getHostName());
//        record.setWarehouseSn(meter.getWarehouseSn());
//        record.setWarehouseName(meter.getWarehouseName());
//        record.setWarehouseId(meter.getWarehouseId());
//        record.setCompanyName(meter.getCompanyName());
//        record.setMaxHum(meter.getMaxHum());
//        record.setMinHum(meter.getMinHum());
//        record.setMaxTem(meter.getMaxTem());
//        record.setMinTem(meter.getMinTem());
//        record.setCreateTime(LocalDateTime.now());
//        record.setWarehouseId(meter.getWarehouseId());  // 重复设置，可能是笔误
//        record.setHostId(meter.getHostId());
//        return record;
//    })
//            .map(meterRecordMapper::insert)  // 插入数据库
//        .map(count -> count > 0)  // 判断插入是否成功
//            .orElse(false);  // 如果查询结果为空，返回false


    @Override
    public String selectById(String sn) {
        QueryWrapper<Meter> wapper = new QueryWrapper<>();
        wapper.eq("sn", sn);
        List<Meter> meters = meterMapper.selectList(wapper);
        if (meters == null) {
            return null;
        }

        Meter meter = meters.get(0);
// 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        String jsonString = JSON.toJSONString(meter);
        BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(meter.getName());
        ops.put("sn", meter.getSn());
        ops.put("name", meter.getName());
        ops.put("max_hum", String.valueOf(meter.getMaxHum()));
        ops.put("min_hum", String.valueOf(meter.getMinHum()));
        ops.put("max_tem", String.valueOf(meter.getMaxTem()));
        ops.put("min_tem", String.valueOf(meter.getMinTem()));
        ops.put("state", String.valueOf(meter.getState()));
        ops.put("create_time", meter.getCreateTime().format(formatter));
        ops.put("collect_interval", meter.getCollectInterval());

        return meter.getCollectInterval();
    }

    @Override
    public Boolean updateInterval(String sn, String cronExpression) {
        UpdateWrapper<Meter> wapper = new UpdateWrapper<>();
        wapper.eq("sn",sn);
        wapper.set("collect_interval",cronExpression);


//        Meter meter = new Meter();
//        meter.setCollectInterval(cronExpression);
        int update = meterMapper.update(wapper);
        return update>0;
    }
}
